<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Users2_Controller extends CI_Controller {

    function __construct() {

        parent::__construct();
        $this->load->model('user', '', TRUE);
        //$this->load->model('user_list', '', TRUE);
        if (!$this->session->userdata('logged_in')) {

            redirect('login');
        }



        $this->load->library('authentication');
        $this->load->helper('t');

        $this->loggedUser = $this->authentication->getLoggedUser();
        $this->authentication->redirectIfNotBe(array('SS', 'KAS'));
    }

    function index($tlCode = 'all', $title = 'all') {

        $titles = array('NR' => 'NR', 'PG' => 'PG', 'BS' => 'BS', 'Medical' => 'Medical');
        $viewData['titles'] = $titles;

        $this->load->model('region');
        $regions = $this->region->get_list();
        $viewData['regions'] = $regions;

        $regionDic = array();
        foreach ($regions as $key => $value) {
            $regionDic[$value['rsm_code']] = $value['region_name'];
        }
        $viewData['regionDic'] = $regionDic;

        $users = array();
        if ($title != 'all') {
            $viewData['filterTitle'] = $title;
            switch ($title) {
                case 'NR':
                    $users = $this->user->get_list_by_title(array('NR', 'NRTL'), array('status' => 'active', 'supervisor_code' => $this->loggedUser->code));
                    break;
                case 'PG':
                    $users = $this->user->get_list_by_title(array('PG', 'PGTL'), array('status' => 'active', 'supervisor_code' => $this->loggedUser->code));
                    break;
                case 'BS':
                    $users = $this->user->get_list_by_title(array('BS', 'BSTL'), array('status' => 'active', 'supervisor_code' => $this->loggedUser->code));break;
                case 'Medical': 
                    $users = $this->user->get_list_by_title(array('MedNR', 'MedBS', 'MedTL'), array('status' => 'active', 'supervisor_code' => $this->loggedUser->code));
                    break;
            }
        } else {
            $users = $this->user->get_list_by_title(get_employee_titles(), array('status' => 'active', 'supervisor_code' => $this->loggedUser->code));
        }
        if ($tlCode != 'all') {
            $temp = array();
            foreach ($users as $eachUser) {
                if ($eachUser['teamleader_code'] == $tlCode) {
                    $temp[] = $eachUser;
                }
            }
            $users = $temp;
            $viewData['filterRegion'] = $tlCode;
        }


        $viewData['rows'] = $users;


        $this->load->view(get_folder($this->loggedUser->title) . '/users2', $viewData);
    }
    
    function report($tlCode = 'all', $title = 'all') {

        $titles = array('NR' => 'NR', 'PG' => 'PG', 'BS' => 'BS', 'Medical' => 'Medical');
        $viewData['titles'] = $titles;

        $this->load->model('region');
        $regions = $this->region->get_list();
        $viewData['regions'] = $regions;
        
        $teamleaders = $this->user->get_list_by_title(array('NRTL', 'BSTL', 'PGTL', 'MedTL'), array('status' => 'active', 'supervisor_code' => $this->loggedUser->code));
        $viewData['teamleaders'] = $teamleaders;

        $regionDic = array();
        foreach ($regions as $key => $value) {
            $regionDic[$value['rsm_code']] = $value['region_name'];
        }
        $viewData['regionDic'] = $regionDic;

        $users = array();
        if ($title != 'all') {
            $viewData['filterTitle'] = $title;
            switch ($title) {
                case 'NR':
                    $users = $this->user->get_list_by_title(array('NR', 'NRTL'), array('status' => 'active', 'supervisor_code' => $this->loggedUser->code));
                    break;
                case 'PG':
                    $users = $this->user->get_list_by_title(array('PG', 'PGTL'), array('status' => 'active', 'supervisor_code' => $this->loggedUser->code));
                    break;
                case 'BS':
                    $users = $this->user->get_list_by_title(array('BS', 'BSTL'), array('status' => 'active', 'supervisor_code' => $this->loggedUser->code));break;
                case 'Medical': 
                    $users = $this->user->get_list_by_title(array('MedNR', 'MedBS', 'MedTL'), array('status' => 'active', 'supervisor_code' => $this->loggedUser->code));break;
            }
        } else {
            $users = $this->user->get_list_by_title(get_employee_titles(), array('status' => 'active', 'supervisor_code' => $this->loggedUser->code));
        }
        if ($tlCode != 'all') {
            $temp = array();
            foreach ($users as $eachUser) {
                if ($eachUser['teamleader_code'] == $tlCode) {
                    $temp[] = $eachUser;
                }
            }
            $users = $temp;
            $viewData['filterTL'] = $tlCode;
        }

        
        $viewData['rows'] = $users;


        $this->load->view(get_folder($this->loggedUser->title) . '/users2_report', $viewData);
    }

    function edit($user_id) {
        show_404();exit;
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');

        if ($this->input->post('Command') == 'Edit') {
            // Validation
            $this->form_validation->set_rules('username', 'Username', 'required|min_length[4]');
            $this->form_validation->set_rules('identity_number', 'Identity No', 'required');
            $this->form_validation->set_rules('name', 'Name', 'required');
            $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
            
            if ($this->form_validation->run() == FALSE) {
                $viewData['messageType'] = 'danger';
                $viewData['message'] = validation_errors();
            } else {
                // thực hiện cập nhật
                $newUser = array(
                    'id' => $user_id,
                    'name' => $this->input->post('name'),
                    //'code' => $this->input->post('code'), // kéo theo nhiều thứ khác
                    'gid' => $this->input->post('gid'),
                    'starting_day' => $this->input->post('starting_day'),
                    'stopping_day' => $this->input->post('stopping_day') != '' ? $this->input->post('stopping_day') : null,
                    'title' => $this->input->post('title'),
                    'location' => $this->input->post('location'),
                    'status' => $this->input->post('status'),
                    'status2' => $this->input->post('status2'),
                    'teamleader_code' => $this->input->post('teamleader_code'),
                    'supervisor_code' => $this->input->post('supervisor_code'),
                    'rsm_code' => $this->input->post('rsm_code'),
                    'identity_number' => $this->input->post('identity_number'),
                    'address' => $this->input->post('address'),
                    'phone' => $this->input->post('phone'),
                    'email' => $this->input->post('email'),
                    'note' => $this->input->post('note'),
                );
                
                if($this->input->post('password') != '')
                {
                    $newUser['password'] = md5($this->input->post('password'));
                }
                
                $viewData['messageType'] = 'success';
                $message = $this->user->update($newUser);
                $viewData['message'] = $message;
            }
        }

        $user = $this->user->get($user_id);
        $viewData['editUser'] = $user;
        $viewData['titles'] = $this->user->get_enum_values();
        
        $this->load->model('group_model', '', TRUE);
        $viewData['groups'] = $this->group_model->get_allgroups();
        
        $tls = $this->user->get_list_by_title(array('NRTL', 'BSTL', 'PGTL'));
        $sss = $this->user->get_list_by_title(array('SS', 'KAS'));
        $rsms = $this->user->get_list_by_title(array('RSM', 'KAM'));        
        $viewData['teamleaders'] = $tls;
        $viewData['supervisors'] = $sss;
        $viewData['rsms'] = $rsms;

        $this->load->view(get_folder($this->loggedUser->title) . '/user2_edit', $viewData);
    }

    function ajaxlist() {
        $users = $this->user->get_list();
        return json_encode($users);
    }

    function users_report($limit = '0') {

//        $logged_in = $this->session->userdata('logged_in');
//        if ($logged_in['su'] != "1") {
//            exit('Permission denied');
//            return;
//        }

        $data['result'] = $this->user_list->user_list_all($limit);

        $data['title'] = "User list";

        $data['limit'] = $limit;



        $this->load->view(get_folder($this->loggedUser->title) . '/users_report', $data);
    }

    function remove_user($id) {

        $logged_in = $this->session->userdata('logged_in');

        if ($logged_in['title'] != "HR") {

            exit('Permission denied');

            return;
        }



        $this->user_list->remove_user($id);



        redirect(get_folder($this->loggedUser->title).'/users', 'refresh');
    }

// add new user form

    function add_new($resultstatus = '') {

        $logged_in = $this->session->userdata('logged_in');

        if ($logged_in['title'] != "HR") {

            exit('Permission denied');

            return;
        }

        $data['resultstatus'] = $resultstatus;

        $data['title'] = "Thêm nhân viên mới";

        $data['su'] = $logged_in['title'];

        $data['title_user'] = $this->user_list->get_enum_values();

        //get the list of the groups

        $data['allgroups'] = $this->group_model->get_allgroups();

        //$this->load->view('header', $data);

        $this->load->view(get_folder($this->loggedUser->title) . '/add_user', $data);

        //$this->load->view('footer', $data);
    }

// insert user into database

    function insert_user() {

        $logged_in = $this->session->userdata('logged_in');

        if ($logged_in['title'] != "HR") {

            exit('Permission denied');

            return;
        }

        $this->form_validation->set_rules('username', 'Username', 'required|min_length[4]|is_unique[users.username]');

        $this->form_validation->set_rules('identity_number', 'Identity No', 'required');

        $this->form_validation->set_rules('name', 'Name', 'required');

        $this->form_validation->set_rules('user_email', 'Email', 'required|valid_email|is_unique[users.email]');

        if ($this->form_validation->run() == FALSE) {

            $this->add_new();
        } else {

            $resultstatus = $this->user_list->insert_user();

            $this->add_new($resultstatus);
        }
    }

   
    // edit the user form

    public function edit_user($user_id, $resultstatus = '') {

        $logged_in = $this->session->userdata('logged_in');

        if ($logged_in['title'] != "HR") {

            exit('Permission denied');

            return;
        }

        $logged_in = $this->session->userdata('logged_in');

        $data['title'] = "Edit User";

        $data['resultstatus'] = $resultstatus;

        $data['user'] = $this->user->get_user($user_id);

        $data['title_user'] = $this->user_list->get_enum_values();

        $data['allgroups'] = $this->group_model->get_allgroups();

        $data['user_id'] = $user_id;

        $data['su'] = $logged_in['su'];

        $this->load->view(get_folder($this->loggedUser->title) . '/edit_user', $data);
    }

    // edit the user form

    public function my_account($resultstatus = '') {

        $data['title'] = "Edit User";

        $logged_in = $this->session->userdata('logged_in');

        $user_id = $logged_in['id'];

        $data['user'] = $this->user->get_user($logged_in['id']);

        $data['allgroups'] = $this->group_model->get_allgroups();

        $data['user_id'] = $user_id;

        $data['resultstatus'] = $resultstatus;

        $data['su'] = $logged_in['su'];

        $this->load->view('header', $data);

        $this->load->view('edit_user', $data);

        $this->load->view('footer', $data);
    }

    // update user in database

    function update_user($user_id) {

        // form validations

        $logged_in = $this->session->userdata('logged_in');

        if ($logged_in['su'] == "0") {

            $user_id = $logged_in['id'];
        }

        $this->form_validation->set_rules('username', 'Username', 'required|min_length[4]');

        $this->form_validation->set_rules('identity_number', 'Identity No', 'required');

        $this->form_validation->set_rules('name', 'Name', 'required');

        $this->form_validation->set_rules('user_email', 'Email', 'required|valid_email');



        if ($this->form_validation->run() == FALSE) {

            $this->edit_user($user_id);
        } else {

            $resultstatus = $this->user_list->update_user($user_id);

            $this->edit_user($user_id, $resultstatus);
        }
    }

}
